package com.leyou.cart.service;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.filter.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 冯金平 on 2023/3/23 11:26
 */
@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;//格式便于查看注意模板
    @Autowired
    private GoodsClient goodsClient;

    //本地user存储到REDIS前缀，购物车MAP<K-UID,MAP<K-SHOPID,V-SHOPDetail>>
    private static final String KEY_PREFIX = "leyou:cart:uid:";

    public void addCart(Cart cart) {
//        登录状态按下用户购物车有商品则更新对应的商品数量，前台可以操作的单一商品属性
        //获取登录用户
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //存储的KEY
        String userKey = KEY_PREFIX+loginUser.getId();//购物车ID
        //前台返回的数据
        String key = cart.getSkuId().toString();//skuId是购物车的商品ID
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        //得到redis的hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(userKey);
        //判断用户购物车是否有这个商品
        Boolean aBoolean = hashOps.hasKey(key);
        if (aBoolean){
            //获取之前的数据
            String JsonCart = hashOps.get(key).toString();
            //获取到的JSON 数据反序列化为对象
            cart = JsonUtils.parse(JsonCart, Cart.class);
            //更新数量,cart临时变量已经被覆盖get是之前的num是新加入的
            cart.setNum(cart.getNum()+num);

        }else {
//       购物车 没有商品则新建购物车，数量设置为传值
//        查询购物车其他数据赋值
            Sku sku = this.goodsClient.querySkuById(skuId);
            cart.setImage(StringUtils.isBlank(sku.getImages()) ?"":StringUtils.split(sku.getImages(),",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
            cart.setUserId(loginUser.getId());
        }
//         购物车更新之后重写入Redis,序列化为JSON
        hashOps.put(key,JsonUtils.serialize(cart));

    }

    public List<Cart> queryCartList() {
        //获取登录用户
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //判断是之前是否有购物车
        if (!this.redisTemplate.hasKey(KEY_PREFIX+loginUser.getId())){
            return null;
        }
        //登录用户的购物车
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        //redis返回的是cartJson
        List<Object> cartsJson= hashOps.values();
        if (CollectionUtils.isEmpty(cartsJson)){
            return null;
        }
        //转为对象的集合响应
       return cartsJson.stream().map(cart -> JsonUtils.parse(cart.toString(),Cart.class)).collect(Collectors.toList());
    }

    public void updateNum(Cart cart) {
        //获取登录用户
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //判断是之前是否有购物车
        if (!this.redisTemplate.hasKey(KEY_PREFIX+loginUser.getId())){
            return ;
        }
        //登录用户的购物车
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        //redis返回的是cartJson,购物车数据
        String cartJson = hashOps.get(cart.getSkuId().toString()).toString();
        Integer num = cart.getNum();
        cart = JsonUtils.parse(cartJson, Cart.class);
        cart.setNum(num);//前端已经+—这里直接赋值

        //更新购物车数据重写回redis,购物车属于KEY_PREFIX+loginUser.getId(),数据是JsonUtils.serialize(cart)
        hashOps.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));

    }


    public void deleteShop(String skuId) {
        //获取登录用户
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //判断是之前是否有购物车
        if (!this.redisTemplate.hasKey(KEY_PREFIX+loginUser.getId())){
            return ;
        }
        //登录用户的购物车
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        hashOps.delete(skuId);
    }
}
